// pages/verification/verification.js

const app = getApp();
const auth = require('../../utils/clientAuth');

Page({
  data: {
    verifyType: 'phone', // phone 或 email
    identifier: '', // 手机号或邮箱号
    verifyCode: '', // 验证码
    requestId: '', // 验证请求ID
    countdown: 0, // 倒计时
    isSubmitting: false, // 是否正在提交
    isManualVerification: false // 是否是人工验证
  },

  onLoad() {
    // 尝试登录
    this.tryLogin();
  },

  // 尝试登录
  async tryLogin() {
    const success = await auth.login();
    if (success) {
      app.globalData.isLoggedIn = true;
      wx.redirectTo({
        url: '/pages/index/index'
      });
    }
  },

  // 切换验证方式
  handleSwitchType() {
    this.setData({
      verifyType: this.data.verifyType === 'phone' ? 'email' : 'phone',
      identifier: '',
      verifyCode: '',
      requestId: '',
      countdown: 0,
      isManualVerification: false
    });
  },

  // 输入标识符（手机号或邮箱）
  handleIdentifierInput(e) {
    this.setData({
      identifier: e.detail.value
    });
  },

  // 输入验证码
  handleCodeInput(e) {
    this.setData({
      verifyCode: e.detail.value
    });
  },

  // 验证输入
  validateInput() {
    const { verifyType, identifier } = this.data;
    
    if (!identifier) {
      app.showError(verifyType === 'phone' ? '请输入手机号' : '请输入邮箱');
      return false;
    }

    if (verifyType === 'phone') {
      if (!/^1[3-9]\d{9}$/.test(identifier)) {
        app.showError('请输入正确的手机号');
        return false;
      }
    } else {
      if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(identifier)) {
        app.showError('请输入正确的邮箱');
        return false;
      }
    }

    return true;
  },

  // 发送验证码
  async handleSendCode() {
    if (this.data.countdown > 0 || !this.validateInput()) {
      return;
    }

    try {
      app.showLoading('发送验证码...');
      const { requestId } = await auth.sendVerificationCode(
        this.data.verifyType,
        this.data.identifier
      );

      this.setData({
        requestId,
        countdown: 60
      });

      this.startCountdown();
    } catch (err) {
      app.showError(err.message || '发送验证码失败');
    } finally {
      app.hideLoading();
    }
  },

  // 开始倒计时
  startCountdown() {
    if (this.data.countdown <= 0) {
      return;
    }

    setTimeout(() => {
      this.setData({
        countdown: this.data.countdown - 1
      });
      this.startCountdown();
    }, 1000);
  },

  // 切换到人工验证
  handleSwitchToManual() {
    this.setData({
      isManualVerification: true,
      verifyCode: '',
      requestId: ''
    });
  },

  // 提交验证
  async handleSubmit() {
    if (this.data.isSubmitting || !this.validateInput()) {
      return;
    }

    const { verifyType, identifier, verifyCode, requestId, isManualVerification } = this.data;

    if (!isManualVerification && !verifyCode) {
      app.showError('请输入验证码');
      return;
    }

    try {
      this.setData({ isSubmitting: true });
      app.showLoading('验证中...');

      if (isManualVerification) {
        // 提交人工验证申请
        const { requestId } = await auth.sendVerificationCode(
          verifyType,
          identifier,
          'manual'
        );
        
        // 显示等待审核提示
        wx.showModal({
          title: '提交成功',
          content: '您的验证申请已提交，请等待管理员审核',
          showCancel: false,
          success: () => {
            wx.redirectTo({
              url: '/pages/verification/verification?requestId=' + requestId
            });
          }
        });
      } else {
        // 验证码验证
        const res = await auth.verifyCode(requestId, verifyCode);
        
        if (res.status === 'approved') {
          // 验证通过，保存登录态
          auth.saveToken(res.token);
          app.globalData.isLoggedIn = true;
          
          // 跳转到首页
          wx.redirectTo({
            url: '/pages/index/index'
          });
        } else {
          throw new Error('验证失败');
        }
      }
    } catch (err) {
      app.showError(err.message || '验证失败');
    } finally {
      this.setData({ isSubmitting: false });
      app.hideLoading();
    }
  }
});
